/**
 * Copyright (C) 2014  Jonas Lammers
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package mygame;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO: notify listeners more fine grained and not broadcasting every 
 * result to every listener
 * @author jonas
 */
public class CollisionWorld {
    
    private ArrayList<CollisionObject> objectsDynamic;
    private ArrayList<CollisionObject> objectsStatic;
    private ArrayList<CollisionObject> objectsPlayer;
    private ArrayList<CollisionListener> listeners;
    
    private Broadphase b;
    
    public CollisionWorld(){
        this.objectsDynamic = new ArrayList<CollisionObject>();
        this.objectsStatic = new ArrayList<CollisionObject>();
        this.objectsPlayer = new ArrayList<CollisionObject>();
        this.listeners = new ArrayList<CollisionListener>();
        
        b = new Broadphase();
        
    }
    
    public void addCollisionObject(CollisionObject object){
        if(object.isPlayer()){
            this.objectsPlayer.add(object);
        }else if(object.isStatic()){
            this.objectsStatic.add(object);
        }else{
            this.objectsDynamic.add(object);
        }        
    }
    
    public void checkCollisions(){
        b.checkCollisions(objectsPlayer);
        iterateResults(b.getCollisionResultList());
        
        b.checkCollisions(objectsPlayer, objectsDynamic);
        iterateResults(b.getCollisionResultList());
        
        b.checkCollisions(objectsPlayer, objectsStatic);
        iterateResults(b.getCollisionResultList());
        
        b.checkCollisions(objectsDynamic);
        iterateResults(b.getCollisionResultList());
        
        b.checkCollisions(objectsDynamic, objectsStatic);
        iterateResults(b.getCollisionResultList());
    }
    
    private void iterateResults(List<CollisionResult> results){
        for(CollisionResult result: results){
            notifyListeners(result);
        }
    }
    
    private void notifyListeners(CollisionResult result){
        for(CollisionListener listener : listeners){
            listener.collisionDetected(result);
        }
    }
    
    public void addListener(CollisionListener listener){
        this.listeners.add(listener);        
    }
}
